package com.xjh.serverinspect.util;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <p>
 * 数据库连接包装类
 * </p>
 *
 * @author xujinghui
 * @since 2024-10-16
 */
@Getter
@Slf4j
public class ConnectionWrapper {

    /**
     * 是否连接成功
     */
    boolean connected;

    /**
     * 连接错误信息
     */
    String connectionError;

    /**
     * 连接对象
     */
    Connection connection;

    /**
     * 执行查询语句
     *
     * @param sql 查询语句
     * @return ResultSetWrapper
     */
    public ResultSetWrapper executeQuery(String sql) {
        ResultSetWrapper resultSetWrapper = new ResultSetWrapper();
        if (connected) {
            try {
                resultSetWrapper.setResultSet(connection.createStatement().executeQuery(sql));
            } catch (SQLException e) {
                resultSetWrapper.setError(e.getMessage());
            }
        } else {
            resultSetWrapper.setError(connectionError);
        }
        return resultSetWrapper;
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (connected) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("Failed to close connection.", e);
            }
        }
    }

    @Setter
    @Getter
    public static class ResultSetWrapper {
        private ResultSet resultSet;
        private String error;
    }

}
